//
//  SellDetialViewController.m
//  Manager
//
//  Created by Mr.Lee on 2018/4/18.
//  Copyright © 2018年 Reabam. All rights reserved.
//

#import "SellDetialViewController.h"
#import "SellConditionDetialController.h"
#import "MJRefresh.h"
#import "TSFooterRefresh.h"                 // 刷新
#import "TSHeaderRefresh.h"
#import "CommercialModel.h"
//#import "CommercialCell.h"
#import "CommerDetialCell.h"
@interface SellDetialViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    UITableView *table;
    NSString *_orderSort;
    UIView *tableHeaderView;
    UIButton *sat; // 商品
    UIButton *sat1; // 订单数
    UIButton *sat2; // 销售额
    BOOL saveAccount;
    
    int pageNumber;
    NSString *pageSize;
    NSString *result;
    NSString*TotalCount;
    UIView*noDataView;
    NSMutableArray*modelArray;
    
    // 筛选
    NSString *orderField;
}
@property (nonatomic, strong) NSString *sats;
@end

@implementation SellDetialViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    pageSize = @"20";
    // 品类
    if ([self.type isEqualToString:@"pinlei"]) {
        self.title = @"品类销量明细";
    // 商品销量
    } else{
        self.title = @"商品销量明细";
    }
    
    modelArray = [NSMutableArray array];
    orderField = @"amount";
    _orderSort = @"desc";
    
    
    UILabel *timeLabel = [[UILabel alloc] init];
    timeLabel.frame = CGRectMake(0, 0, ScreenWidth, 30);
//    self.timeLabel = timeLabel;
    timeLabel.font = [UIFont systemFontOfSize:13.0];
    timeLabel.textColor = lanse;//[UIColor colorWithHexString:@"cccccc"];
    timeLabel.textAlignment = NSTextAlignmentCenter;
    timeLabel.backgroundColor = [UIColor colorWithHexString:@"f4f4f4"];
    
    if ([_beginDate isEqualToString:_endDate]) {
        timeLabel.text = _beginDate;
    } else{
        timeLabel.text = [NSString stringWithFormat:@"%@~%@", _beginDate, _endDate];
    }
    [self.view addSubview:timeLabel];

    // 设置HeaderView
    [self tableHeaderView];
    
    // tableView
    [self addTable];
    
    // 集成刷新控件
    [self setUpRefresh];
    
    // 数据请求
    [self requestData];
}



-(void)tableHeaderView{

    
    tableHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 30, ScreenWidth,40)];
    tableHeaderView.backgroundColor= [UIColor whiteColor];
    [self.view addSubview:tableHeaderView];
    
    // 商品
    sat=[[UIButton alloc]initWithFrame:CGRectMake(15, 0, ScreenWidth/3-15, 40)];
    [sat setTitle:@"门店名称" forState:UIControlStateNormal];
    [sat setTitleColor:[UIColor colorWithHexString:@"141e34"] forState:UIControlStateNormal];
    sat.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
    sat.titleLabel.font=[UIFont systemFontOfSize:13];
    [tableHeaderView addSubview:sat];
    
    // 销售量
    sat1=[[UIButton alloc]initWithFrame:CGRectMake(sat.right, 0, ScreenWidth/3, 40)];
    [sat1 setTitle:@"销售量" forState:UIControlStateNormal];
    [sat1 setTitleColor:[UIColor colorWithHexString:@"141e34"] forState:UIControlStateNormal];
    sat1.titleLabel.font=[UIFont systemFontOfSize:13];
    [sat1 addTarget:self action:@selector(sat1:) forControlEvents:UIControlEventTouchUpInside];
    [sat1 setImage:[UIImage imageNamed:@"jiantou_normal"] forState:UIControlStateNormal];
    [sat1 setTitleEdgeInsets:UIEdgeInsetsMake(0, -sat1.imageView.size.width, 0, sat1.imageView.size.width)];
    [sat1 setImageEdgeInsets:UIEdgeInsetsMake(0, sat1.titleLabel.bounds.size.width, 0, -sat1.titleLabel.bounds.size.width)];
    [tableHeaderView addSubview:sat1];
    
    // 销售额
    sat2=[[UIButton alloc]initWithFrame:CGRectMake(sat1.right , 0, ScreenWidth/3, 40)];
    [sat2 setTitle:@"销售额" forState:UIControlStateNormal];
    [sat2 setTitleColor:[UIColor colorWithHexString:@"141e34"] forState:UIControlStateNormal];
    sat2.titleLabel.font=[UIFont systemFontOfSize:13];
    [sat2 addTarget:self action:@selector(sat2:) forControlEvents:UIControlEventTouchUpInside];
    [sat2 setImage:[UIImage imageNamed:@"xia_hight"] forState:UIControlStateNormal];
    [sat2 setTitleEdgeInsets:UIEdgeInsetsMake(0, -sat2.imageView.size.width, 0, sat2.imageView.size.width)];
    [sat2 setImageEdgeInsets:UIEdgeInsetsMake(0, sat2.titleLabel.bounds.size.width, 0, -sat2.titleLabel.bounds.size.width)];
    [tableHeaderView addSubview:sat2];
    
    UIView *lineView = [[UIView alloc] init];
    lineView.frame = CGRectMake(0, 40-0.5, ScreenWidth, 0.5);
    lineView.backgroundColor = qianhuiColor; // [UIColor redColor];//
    [tableHeaderView addSubview:lineView];

    saveAccount = NO;
}

// 销售量
-(void)sat1:(UIButton*)sender{
    saveAccount=!saveAccount;
    orderField = @"saleQty";
    if (saveAccount) {
        _orderSort=@"asc";
        [sat1 setImage:[UIImage imageNamed:@"shang_hight"] forState:UIControlStateNormal];
        
    }else{
        _orderSort=@"desc";
        [sat1 setImage:[UIImage imageNamed:@"xia_hight"] forState:UIControlStateNormal];
    }
    [sat2 setImage:[UIImage imageNamed:@"jiantou_normal"] forState:UIControlStateNormal];
    [self requestData];
}

// 销售额
-(void)sat2:(UIButton*)sender{
    saveAccount=!saveAccount;
    orderField = @"amount";
    if (saveAccount) {
        _orderSort=@"asc";
        [sat2 setImage:[UIImage imageNamed:@"shang_hight"] forState:UIControlStateNormal];
        
    }else{
        _orderSort=@"desc";
        [sat2 setImage:[UIImage imageNamed:@"xia_hight"] forState:UIControlStateNormal];
    }
    [sat1 setImage:[UIImage imageNamed:@"jiantou_normal"] forState:UIControlStateNormal];
    [self requestData];
}



-(void)addTable{
    
    [table removeFromSuperview];
    table = [[UITableView alloc]initWithFrame:CGRectMake(0,tableHeaderView.bottom, ScreenWidth, ScreenHeight-64- tableHeaderView.height-30) style:UITableViewStylePlain];
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    table.delegate=self;
    table.dataSource=self;
    [self.view addSubview:table];
}
// 刷新
- (void)setUpRefresh {
    table.mj_footer = [TSFooterRefresh footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreProductList)];
}

-(void)requestData{
    pageNumber=1;
    [noDataView removeFromSuperview];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"1" forKey:@"pageIndex"];
    [param setValue:pageSize forKey:@"pageSize"];
    //    排序字段 orderCount按单数 amount按金额
    [param setValue:orderField forKey:@"orderField"];
    //    排序方式 asc升序 desc降序
    [param setValue:_orderSort forKey:@"orderSort"];

    [param setValue:_beginDate forKey:@"beginDate"];
    [param setValue:_endDate forKey:@"endDate"];
    
    NSString *url = nil;
    // 品类
    if ([self.type isEqualToString:@"pinlei"]) {
        url = @"report/item/itemTypeSalesDetail";
        [param setValue:_mTypeCode forKey:@"mTypeCode"];
    // 商品销量
    } else{
        [param setValue:_itemId forKey:@"itemId"];
        [param setValue:_specId forKey:@"specId"];
        url = @"report/item/itemSalesDetail";
    }
    
    NSLog(@"%@", param);
    [MBProgressHUD showIndeterminateHudSub:@"" delay:30 view:self.view];
    [HttpRequest requestData:url params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        NSLog(@"====%@",severDataDict.dataDict);
        if (isSuccess) {
            [modelArray removeAllObjects];
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [MBProgressHUD hideProgressHUDInternal:self.view];
                NSMutableArray* arrr=[[NSMutableArray alloc] init];
                arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                if (arrr.count == 0) {
                    noDataView=[[UIView alloc]initWithFrame:CGRectMake(0, (ScreenHeight-64-49)/2-50, ScreenWidth, 80)];
                    [self.view addSubview:noDataView];
                    UIImageView*noImage=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-47, 0, 94, 51)];
                    
                    UIImage *image1 = nil;
                    if ([self.type isEqualToString:@"shangpin"]) {
                        image1= [UIImage imageNamed:@"meiyoushuju"];
                    } else{
                        image1= [UIImage imageNamed:@"meiyoushuju"];
                    }
                    
                    noImage.image = image1;
                    [noDataView addSubview:noImage];
                    UILabel*noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,65, ScreenWidth, 14)];
                    noLabel.text=@"没有列表数据！";
                    noLabel.textColor=zhonghuiColor; noLabel.font=[UIFont systemFontOfSize:14];
                    noLabel.textAlignment=NSTextAlignmentCenter;
                    [noDataView addSubview:noLabel];
                } else{
                    for (NSDictionary* dicc in arrr ) {
                        CommercialModel *model =[CommercialModel  mj_objectWithKeyValues:dicc];
                        [modelArray addObject:model];
                    }
                }
                
                [table reloadData];
                
                NSString *orderCountTotal = [NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"orderCountTotal"]];
                NSString *salesTotal = [NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"salesTotal"]];
                NSString *beginDate = [NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"beginDate"]];
                NSString *endDate = [NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"endDate"]];
                
                TotalCount= [NSString stringWithFormat:@"%@", [severDataDict.dataDict objectForKey:@"TotalCount"]];
                if (TotalCount.intValue < pageSize.intValue) {
                    [table.mj_footer endRefreshingWithNoMoreData];
                } else if(TotalCount.intValue > pageSize.intValue){
                    [table.mj_footer resetNoMoreData];
                }
            }else{
                [MBProgressHUD hideProgressHUDInternal:self.view];
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    LoginViewController *loginVC=[[LoginViewController alloc] init];//2.0{9个参数 少2个}
                    [self.navigationController pushViewController:loginVC animated:YES];
                }
                NSString *subStr = [severDataDict.dataDict objectForKey:@"ResultString"];
                [MBProgressHUD showTextHudSub:subStr view:self.view];
            }
            
        } else {
            [MBProgressHUD hideProgressHUDInternal:self.view];
            NSString *subStr = [severDataDict.dataDict objectForKey:@"ResultString"];
            [MBProgressHUD showTextHudSub:subStr view:self.view];
        }
        
    }];
    
}

// 上拉刷新
- (void)loadMoreProductList{
    if (TotalCount.floatValue/pageSize.floatValue > pageNumber) {
        pageNumber++;
        NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
        NSString* tokenId = [user1 objectForKey:@"tokenId"];
        NSMutableDictionary *params = [NSMutableDictionary new];
        [params setValue:tokenId forKey:@"tokenId"];
        [params setValue:[NSString stringWithFormat:@"%d" ,pageNumber] forKey:@"pageIndex"];
        [params setValue:pageSize forKey:@"pageSize"];
        [params setValue:orderField forKey:@"orderField"];
        //    排序方式 asc升序 desc降序
        [params setValue:_orderSort forKey:@"orderSort"];
        
        [params setValue:_beginDate forKey:@"beginDate"];
        [params setValue:_endDate forKey:@"endDate"];
        
        NSString *url = nil;
        // 品类
        if ([self.type isEqualToString:@"pinlei"]) {
            url = @"report/item/itemTypeSalesDetail";
            [params setValue:_mTypeCode forKey:@"mTypeCode"];
            // 商品销量
        } else{
            [params setValue:_itemId forKey:@"itemId"];
            [params setValue:_specId forKey:@"specId"];
            url = @"report/item/itemSalesDetail";
        }
        [MBProgressHUD showIndeterminateHudSub:@"" delay:30 view:self.view];
        [HttpRequest requestData:@"report/SalesSummary/statisticsList" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [MBProgressHUD hideProgressHUDInternal:self.view];
                    NSMutableArray* arrr=[[NSMutableArray alloc]init];
                    arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                    for (NSDictionary* dicc in arrr ) {
                        CommercialModel *model =[CommercialModel  mj_objectWithKeyValues:dicc];
                        [modelArray addObject:model];
                    }
                    
                    
                    [table reloadData];
                    TotalCount=[severDataDict.dataDict objectForKey:@"TotalCount"];
                    if (TotalCount.intValue < pageSize.intValue) {
                        [table.mj_footer endRefreshingWithNoMoreData];
                    } else if(TotalCount.intValue >pageSize.intValue){
                        [table.mj_footer resetNoMoreData];
                    }
                }else {
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
                }
                
            } else {
                [MBProgressHUD hideProgressHUDInternal:self.view];
                NSString *subStr = [severDataDict.dataDict objectForKey:@"ResultString"];
                [MBProgressHUD showTextHudSub:subStr view:self.view];
            }
            
        }];
    }else{
        NSString *requestResultStr=@"没有更多数据了！";
        [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
        [table.mj_footer endRefreshingWithNoMoreData];
        
    }
}




#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return modelArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    CommercialModel *model = modelArray[indexPath.row];
    CommerDetialCell *cell = [CommerDetialCell commerDetialCellFromXib:tableView];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.nameLabel.text = model.companyName;
    cell.countLabel.text = model.saleQty;
    
    double saleAmount = [model.saleAmount doubleValue];
    cell.moneyLabel.text = [NSString stringWithFormat:@"%.2f", saleAmount];
    return cell;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  48;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    CommercialModel *model = modelArray[indexPath.row];
//    SellConditionDetialController *vc = [[SellConditionDetialController alloc] init];
//    vc.title = model.companyName;
//    vc.companyId = model.companyId;
//    vc.view.backgroundColor = [UIColor whiteColor];
//    [self.navigationController pushViewController:vc animated:YES];
}


//- (void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
//    [self.navigationController setNavigationBarHidden:NO animated:YES];
//}
//






@end
